/*FavoriteTags.java
 * This class displays the configure favorite tags screen
 * 
 *  Shared Preferences code based on example from http://developer.android.com/guide/topics/data/data-storage.html
 *  Alert Dialog code based on example from http://developer.android.com/guide/topics/ui/dialogs.html
 *  Toast code based on http://developer.android.com/guide/topics/ui/notifiers/toasts.html
 * 	This favorite tag view was build using the information from:
 * 	http://developer.android.com/resources/tutorials/views/hello-formstuff.html
 * 
 */
package com.tagit;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.tagit.PhotosDbAdapter;

public class FavoriteTags extends Activity {

	Button btDone;
	int flag; //Flag to indicate whether or not 'Recommended' button clicked
	String tag;
	int configFlag;
	public static final String PREFS_NAME = "MyPrefsFile"; // Store Favorite tag booleans
															// and strings here

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.favorite_tags);

		// Set listener for Done button
		btDone = (Button) findViewById(R.id.done);
		btDone.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});

		//Set listeners for Favorite Tag buttons
		setFavoriteClickListener();
		
		//Init counter for number of configs to 0
		configFlag = 0;
	}
	
	@Override
	public void onPause(){
		super.onPause();
		
		Context context = getApplicationContext();
		int duration = Toast.LENGTH_SHORT;
		Toast toast;
		
		//Show confirmation message if button configured
		if(configFlag>0){
			CharSequence text = "Favorites updated";
			toast = Toast.makeText(context, text, duration);
			toast.show();
		}
		configFlag = 0;
	}

	// Method for when user clicks done, finishes current Activity
	public void setDoneClickListener() {
		Button DoneButton = (Button) findViewById(R.id.done);
		DoneButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	}

	// Method to set text on buttons
	public void setButtonText(Button button, int num) {
		String text = new String();

		// Keys for shared preferences file
		String favKey = Integer.toString(num) + "F";
		String algoKey = Integer.toString(num) + "A";
		String favString = Integer.toString(num) + "S";

		// Access shared preferences file and if button already recommended or
		// set to string
		SharedPreferences settings = button.getContext().getSharedPreferences(
				PREFS_NAME, Context.MODE_PRIVATE);
		boolean fav = settings.getBoolean(favKey, false); // True if already set
															// to string
		boolean algo = settings.getBoolean(algoKey, false); // True if already
															// recommended

		// If recommended, show, otherwise show the string; if not recommended
		// or string, set to "?"
		if (fav) {
			text = settings.getString(favString, "?");
		} else if (algo) {
			text = "Recommended";
		} else {
			text = "?";
		}
		button.setText(text);
	}

	// Listener method for the 6 Favorite Tags buttons
	public void setFavoriteClickListener() {
		final CharSequence[] favOptions = { "Recommend a tag", "Pick a tag" };

		// Create and set listeners for each of the Favorite Tags buttons
		final Button F1Button = (Button) findViewById(R.id.favorite1);
		setButtonText(F1Button, 1);
		F1Button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				favButtonClick(v, 1, favOptions, F1Button);
			}
		});

		final Button F2Button = (Button) findViewById(R.id.favorite2);
		setButtonText(F2Button, 2);
		F2Button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				favButtonClick(v, 2, favOptions, F2Button);
			}
		});

		final Button F3Button = (Button) findViewById(R.id.favorite3);
		setButtonText(F3Button, 3);
		F3Button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				favButtonClick(v, 3, favOptions, F3Button);
			}
		});

		final Button F4Button = (Button) findViewById(R.id.favorite4);
		setButtonText(F4Button, 4);
		F4Button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				favButtonClick(v, 4, favOptions, F4Button);
			}
		});

		final Button F5Button = (Button) findViewById(R.id.favorite5);
		setButtonText(F5Button, 5);
		F5Button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				favButtonClick(v, 5, favOptions, F5Button);
			}
		});

		final Button F6Button = (Button) findViewById(R.id.favorite6);
		setButtonText(F6Button, 6);
		F6Button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				favButtonClick(v, 6, favOptions, F6Button);
			}
		});
	}

	
	/*Method for when a user clicks on a Favorite tags button - shows an alert dialog
	 * prompting the user to configure the button to either be a recommended tag or 
	 * a previously created tag
	 */
	public void favButtonClick(View v, final int num,
			CharSequence[] favOptions, final Button button) {
		AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()); //Init alert dialg builder
		builder.setTitle("Configure this favorite tag to:");
		
		//Add option to choose either recommended or previous tag
		//Set flag based on results
		builder.setSingleChoiceItems(favOptions, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						if (whichButton == 1) {
							listDialog(button, num);
						} else {
							if (flag == 1) {
								flag = 0;
							} else {
								flag = 1;
							}
						}
					}
				});
		
		//Add continue bottom at bottom of alert dialog
		builder.setPositiveButton("Continue",
				new DialogInterface.OnClickListener() {

					SharedPreferences settings = button.getContext()
							.getSharedPreferences(PREFS_NAME,
									Context.MODE_PRIVATE);

					//If the user chooses recommended, check that this isn't the second click, then
					//set configure button text to "Recommended" and store true in the num+A value in the
					//preferences file (indicating true for algorithmic)
					public void onClick(DialogInterface dialog, int id) {
						SharedPreferences.Editor editor = settings.edit();
						if (flag == 1) {
							
							String algoKey = Integer.toString(num) + "A";
							String strKey = Integer.toString(num) + "F";
							if (settings.getBoolean(algoKey, false)) {
								//editor.remove(algoKey);
							} else{
								editor.putBoolean(algoKey, true);
								editor.putBoolean(strKey, false);
								button.setText("Recommended");
								configFlag++;
							}
							editor.commit();
						}
					}
				});

		AlertDialog alert = builder.create();
		alert.show();
	}

	/*
	 * Helper method for second alert dialog that appears when user clicks on
	 * "pick tag" 
	 */

	public void listDialog(final Button button, final int num) {
		configFlag++;
		PhotosDbAdapter mDb = new PhotosDbAdapter(this);
		mDb.open();

		// Get list of all tags from db and convert to CharSequences
		final List<String> tags = mDb.getAllTags();
		final CharSequence[] items = new CharSequence[tags.size()];
		for (int i = 0; i < tags.size(); i++) {
			items[i] = ((CharSequence) tags.get(i));
		}


		//Build an Alert Dialog asking user to set one of the tags as a favorite
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Pick a tag to set as favorite");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			SharedPreferences settings = button.getContext()
					.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

			//Set button's text to chosen tag, store true for button's boolean key 
			// for num+F and the chosen tag for the button's string key (num+S)
			public void onClick(DialogInterface dialog, int item) {
				button.setText(items[item]);
				String favKey = Integer.toString(num) + "F";
				String favString = Integer.toString(num) + "S";
				SharedPreferences.Editor editor = settings.edit();
				editor.putString(favString, (String) items[item]);
				editor.putBoolean(favKey, true);
				editor.commit();
			}
		});

		//Create and show the alert dialog
		AlertDialog alert = builder.create();
		alert.show();
	}

}